import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:ui';

import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../entity/borrow_again_entity.dart';
import '../entity/reader_entity.dart';
import '../http/api.dart';
import '../main.dart';
import '../util/timer_manager.dart';
import '../util/toast_util.dart';
import '../widget/circle_progress_widget.dart';
import '../widget/clipper.dart';
// import 'package:image/image.dart' as imglib;



class Mine extends StatefulWidget {
  const Mine({Key? key}) : super(key: key);

  @override
  State<Mine> createState() => _MineState();
}

class _MineState extends State<Mine> {

  final RxList<ReaderCurrentBorrowList> _list = RxList();

  late ReaderEntity readerEntity;

  RxBool isEmpty = RxBool(false);

  RxBool pause = RxBool(false);
  RxBool initialize = RxBool(false);
  late List<CameraDescription> _cameras;
  CameraController? controller;

  Timer? _timer;

  var countTime = 120;


  @override
  initState() {
    super.initState();

    readerEntity = Get.arguments;
    checkFace();

    if(readerEntity.currentBorrowList != null ){
      _list.addAll(readerEntity.currentBorrowList!);
    }


    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.normal,(){
        if(Get.isDialogOpen != null && Get.isDialogOpen!){
          Get.back();
        }
        currentTask.clear();
        Get.back();
      });
    });

  }

  _start(){
    countTime = settingEntity.normalCountdown??120;
    _timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      if (countTime <= 0) {
        if(_timer!=null){
          _timer!.cancel();
          _timer = null;
        }
        return;
      }
      countTime = countTime-5;
      _computeTakePicture();

    });
  }
  late CameraImage cameraImage;

  _computeTakePicture() async {
    if (controller != null) {
      XFile file = await controller!.takePicture();
      // var buyt = await compute(_preprocessImage,cameraImage);
      // var data = await compute(_sendPicture, (file,currentTask));
      var bytes = await file.readAsBytes();
      String base64 = base64Encode(bytes);
      String base64Image = "data:image/png;base64,$base64";
      var data = await faceAdd(currentTask.uid,currentTask.uName,base64Image);
      File f = File.fromUri(Uri.file(file.path));
      f.delete();
      if(data.$1 ){
        if(controller != null){
          toastWarn('认证成功');
          tts.speak("认证成功");
          _timer?.cancel();
          _timer = null;
          pause.value = true;
          await controller!.pausePreview();
        }
      }else{
        toastWarn('${data.$2}');
      }
    }
  }

  checkFace() async {
    isEmpty.value = await faceQuery(readerEntity.no!);
  }


  _openCamera() async {
    _cameras = await availableCameras();
    controller = CameraController(_cameras[0], ResolutionPreset.high);
    controller!.initialize().then((_) {
      initialize.value = true;
      _start();
    }).catchError((Object e) {
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            toastError('Camera CameraAccessDenied');
            break;
          default:
            toastError('camera error');
            _disposeCamera();
            break;
        }
      }
    });

  }


  _disposeCamera(){
    _timer?.cancel();
    _timer = null;
    initialize.value = false;
    try{
      controller?.dispose();
      controller = null;
    }catch(e){
      print(e);
    }

  }

  @override
  void dispose() {
    _disposeCamera();
    super.dispose();
  }

  _title(){
    return Container(
        margin: EdgeInsets.only(top:10.h,left: 12.w,right: 12.w),
        width: double.infinity,
        height: 60.h,
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Positioned(
              left: 0,
              child:  InkWell(
                onTap: (){
                  currentTask.clear();
                  timer.cancel();
                  Get.back();
                },
                child: Image.asset("assets/images/back.png",width:80.w, fit: BoxFit.fitWidth,),
              ),
            ),
            Text("个人信息",style: TextStyle(color: const Color.fromRGBO(29, 125, 168, 1),fontSize: 16.sp,fontWeight: FontWeight.bold),),
            Positioned(
              right: 0,
              child:Obx(() => Text("${timer.normalTime.value}s",style: TextStyle(color: Colors.white,fontSize: 12.sp),))
            ),
          ],
        )
    );
  }

  _personInfo(){
    return Container(
        height: 110.h,
        margin: EdgeInsets.only(top: 10.h,left: 12.w,right: 12.w),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned(
              left: 0,
              child: Image.asset("assets/images/head.png", width:70.w, height:70.w,fit: BoxFit.fill,),
            ),
            Positioned(
              left: 80.w,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(readerEntity.name??'',style: TextStyle(color: Colors.blue,fontWeight: FontWeight.bold,fontSize: 14.sp),),
                  SizedBox(height: 3.h,),
                  Text('读者证号:${readerEntity.no}',style: TextStyle(color: Colors.blue,fontSize: 10.sp)),
                  InkWell(
                    onTap: (){
                      if(controller == null){
                        _openCamera();
                      }
                    },
                    child: Row(
                      children: [
                        Obx(() => isEmpty.value?Text('人脸登录:已注册  ',style: TextStyle(color: Colors.blue,fontSize: 10.sp))
                            : Text('人脸登录:未注册  ',style: TextStyle(color: Colors.deepOrangeAccent,fontSize: 10.sp)),),
                        Obx(() => isEmpty.value?Image.asset("assets/images/face_edit.png", width:34.w, fit: BoxFit.fitWidth,)
                            : Image.asset("assets/images/face_register.png", width:34.w, fit: BoxFit.fitWidth,))
                      ],
                    ),
                  )
                ],
              ),
            ),
            Positioned(
                right: 0,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    CircleProgress(size: 60.w,strokeWidth: 3.w,percent: readerEntity.currentBorrowCount!/readerEntity.limitCount!,color: Colors.blue,),
                    Container(
                      width: 50.w,
                      height: 50.w,
                      decoration: BoxDecoration(
                        color: Colors.blue,
                        borderRadius: BorderRadius.all(Radius.circular(25.r)),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text('${readerEntity.currentBorrowCount}/${readerEntity.limitCount}',style: TextStyle(color: Colors.white,fontSize: 12.sp,fontWeight: FontWeight.bold),),
                          Text('借阅数量',style: TextStyle(color: Colors.white,fontSize: 8.sp),)
                        ],
                      ),
                    )
                  ],
                )
            ),

          ],
        )
    );
  }


  _itemBuilder(index){
    var item = _list[index];
    return Container(
      height: 110.h,
      alignment: Alignment.center,
        decoration: BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              item.status==1?"assets/images/person_book_bg_green.png":item.overdue==false?"assets/images/person_book_bg_blue.png":"assets/images/person_book_bg_red.png"
            ),
          )
        ),
      child: Stack(
        children: [
          Positioned(
            top: 15.h,
            left: 15.w,
            right: 75.w,
            child: Text('${item.bookTitle}',maxLines:1,overflow: TextOverflow.ellipsis,style: TextStyle(color: Colors.black,fontSize: 12.sp,fontWeight: FontWeight.bold),),
          ),
          Positioned(
            top: 40.h,
            left: 15.w,
            child: Text('图书编号: ${item.bookNo}',style: TextStyle(color: Colors.black,fontSize: 10.sp),),
          ),
          Positioned(
            top: 55.h,
            left: 15.w,
            child: Text('归还时间: ${item.readyReturnDate}',style: TextStyle(color: Colors.black,fontSize: 10.sp),),
          ),
          Positioned(
            top: 72.h,
            left: 15.w,
            child: Text(item.error != null?'提示信息: ${item.error}':'',style: TextStyle(color: Colors.red,fontSize:12.sp),),
          ),

          Positioned(
            top: 11.h,
            right: 28.w,
            child: Text(item.status==1?'已续借':item.overdue==false?'已借阅':'已超时',style: TextStyle(color: Colors.white, fontSize: 12.sp),),
          ),

          Positioned(
            bottom: 12.h,
            right: 10.w,
            child: InkWell(
              onTap: (){
                if(item.status==0){
                  _borrowAgain(item);
                }
              },
              child: Image.asset(item.status==1?"assets/images/borrow_success.png":"assets/images/borrow_again.png", width:84.w, fit:BoxFit.fitWidth),
            )
          ),

        ],
      )
    );
  }

  _borrowAgain(ReaderCurrentBorrowList item) async {
    var res = await bookBorrowAgain(currentTask.uid, item.bookNo);
    BorrowAgainEntity? data = res.$1;
    if(data != null){
      var index = _list.indexOf(item);
      _list.remove(item);
      item.status = 1;
      item.readyReturnDate = data.readyReturnDate;
      _list.insert(index, item);
    }else{
      var index = _list.indexOf(item);
      _list.remove(item);
      item.error = res.$2;
      _list.insert(index, item);
    }
  }

  _booksContainer(){
    return Container(
      padding: EdgeInsets.only(top: 16.h,left: 4.w,right: 4.w),
      decoration:BoxDecoration(
        color: const Color.fromRGBO(242,254, 255, 1),
        borderRadius: BorderRadius.only(topLeft:Radius.circular(8.r),topRight:Radius.circular(8.r)),
      ),
      child: Obx(() => initialize.value?
        Stack(
          children: [
            Positioned(
              left: 0,
              right: 0,
              top: 10.h,
              child:  Align(
                child: Transform.scale(
                  scale: 1,
                  child: ClipOval(
                    clipper: ClipperOvalPath(300.w,0),
                    child: AspectRatio(
                        aspectRatio: 0.56,
                        child: CameraPreview(controller!)
                    ),
                  ),
                )
              ),
            ),
            Positioned(
                left: 130.w,
                right: 130.w,
                top: 320.h,
                child: InkWell(
                  onTap: (){
                    initialize.value = false;
                    _disposeCamera();
                    if(pause.value){
                      checkFace();
                    }
                  },
                  child: Image.asset("assets/images/${pause.value?'confirm':'cancel'}.png",),
                )
            ),
            if(pause.value)...[
              Positioned(
                left: 0,
                right: 0,
                top: 390.h,
                child: InkWell(
                  child: Align(child: Text('照片不满意？重拍',style: TextStyle(fontSize: 10.sp, decoration: TextDecoration.underline, color:const Color.fromRGBO(255, 26, 26, 1)),),),
                  onTap: () async {
                    if(controller != null){
                      pause.value = false;
                      controller!.resumePreview();
                      _start();
                    }else{
                      toastWarn('camera error');
                    }
                  },
                )
              ),

            ]
          ],
        ):
        ListView.builder(
          itemBuilder: (context, index) {
            return _itemBuilder(index);
          },
          itemCount: _list.length,
        )
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox(
        height: double.infinity,
        width: double.infinity,
        child: Stack(
          children: [
            ImageFiltered(
              imageFilter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
              child: Image.asset("assets/images/index_logo.png"),
            ),
            _title(),
            Positioned(
              top: 46.h,
              left: 0,
              right: 0,
              child: _personInfo(),
            ),
            Positioned(
              top: 160.h,
              left: 0,
              right: 0,
              bottom: 0,
              child: _booksContainer(),
            ),
          ],
        ),
      )
    );
  }
}

